package com.gao.wechat.service.TemplateMessage.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gao.wechat.service.TemplateMessage.TemplateMessageService;



@Service
public class AccessTokenCacheService {

    private Logger LOG = LoggerFactory.getLogger(AccessTokenCacheService.class);
    @Autowired
    private TemplateMessageService templateMessageService;

    static String accessToken_cache = null;

    static Long lastUpdate = null;

    private synchronized void load(String appId, String secret) 
    {
        LOG.debug("重新获取accessToken");
        String accessToken = templateMessageService.getAccessToken(appId, secret);
        if (accessToken != null) {
            accessToken_cache = accessToken;
            lastUpdate = System.currentTimeMillis();
        } else {
            LOG.error("获取accessToken失败 => {} - {}", accessToken, lastUpdate);
        }
    }

    public String getAccessToken(String appId, String secret) 
    {
        if (null == accessToken_cache || System.currentTimeMillis() - lastUpdate > 60 * 60 * 2 * 1000) 
        {
            load(appId, secret);
        }
        return accessToken_cache;
    }
}
